/** \file lp_evaluator.c
 * \brief Parsed tree evaluator.
 * \author Marcelo Lira dos Santos
 * \date 2007
 *
 * This is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License, see the file LICENSE.
 */
#include "lp_evaluator.h"

/** \brief Evaluate the parsed tree writing the results in the TreeModel.
 * \param parsedTreeModel GtkTreeStore
 * \param parent GtkTreeIter
 * \return Calculated value of the proposition.
 */
gboolean
lp_evaluate (GtkTreeStore *parsedTreeModel, GtkTreeIter *parent)
{
	GtkTreeIter children;
	gint nodeType;
	gint nodeId;
	gchar *value;
	gboolean result;
	gboolean left;
	gboolean right;
	
	if (parent)
		gtk_tree_model_get (GTK_TREE_MODEL (parsedTreeModel), parent,
									1, &value,
									2, &nodeType,
									3, &nodeId,
									-1);

	if (gtk_tree_model_iter_children (GTK_TREE_MODEL (parsedTreeModel),
													&children, parent)) {

		left = lp_evaluate (parsedTreeModel, &children);
		result = !left;
		if (gtk_tree_model_iter_next (GTK_TREE_MODEL (parsedTreeModel),
												&children)) {
			right = lp_evaluate (parsedTreeModel, &children);

			switch (nodeType) {
				case C_AND:
					result = left && right;
					break;
				case C_OR:
					result = left || right;
					break;
				case C_IF:
					result = !left || right;
			}
		}
		
		if (parent)	
			gtk_tree_store_set (parsedTreeModel, parent,
										1, (result) ? TRUE_TEXT : FALSE_TEXT,
										-1);

	} else if (nodeType == C_ID)
		result = !g_ascii_strcasecmp (value, TRUE_TEXT);

	return result;
}
